var express = require('express');
var db = require('../config/db');

var libDate = require('../lib/lib_date');
var cache = require('../lib/lib_redis_cache.js');
var redis = require('../lib/lib_redis_cache.js')
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  //res.render('index', { title: 'Express' });
  
  console.log(libDate.formatTime('Y-m-d H:i:s', libDate.time()));
  console.log(libDate.time());
  console.log(libDate.time(true));
  res.send("yiiwan.cn");
});

router.get('/test', function(req, res, next) {
  redis.set('text_key1', 123, 60);

  // db.selectAndCount('app', '*', {status:1}, 'aid', {offset:0, limit:10}, function(err, data){
  //   console.log(err, data);
  // });
  
  var ck = "testList";
  
  cache.get(ck, (err, rows) =>{
    if(rows){
      res.json(rows);
    } else {
      var sql = "SELECT * FROM app";
      db.query(sql, function(err, rows){
        var rsData = new Array();
        //console.log(err, rows);
        for(var i in rows){
          var row = rows[i];
          rsData.push({
            aid : row['aid'],
            name : row['app_name']
          })
        }
        console.log(ck);
        cache.set(ck, rsData, 60);
        
        rsData.push({isNoCache : true});
        res.json(rsData);
      })
    }
  })
  
  //res.send({fsfsdfd:123});
});

router.get('/test/update', function(req, res, next) {
  var sql = "UPDATE app SET status=20 WHERE aid=6";
  db.query(sql, function(err, rows){
    
    console.log(err,rows);
    
    
    res.send(JSON.stringify({data: 'ok'}));
  })
  
  //res.send({fsfsdfd:123});
});

router.get('/format', function(req, res, next){
    var sql = "SELECT * FROM `yx_fkzkw_checkpoint`";
    var errorRowTotal = 0;
    db.query(sql, function(err, rows){
        for(var i in rows){
            var row = rows[i];
            try{
                var checkData = JSON.parse(row.checkpoint_data);

                db.update('yx_fkzkw_checkpoint', {name:checkData.name}, "id="+row.id, function(err, rows){

                })

            } catch(err){
                //删除异常数据
                errorRowTotal++;
                // var sql = "DELETE FROM yx_fkzkw_checkpoint WHERE id=" + row.id;
                // console.log(sql);
                // db.query(sql, (err, rows)=>{
                    
                // })
            }
        }
        console.log(errorRowTotal);
        res.send('format');
    })

    //res.send('format')
})

module.exports = router;
